﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using LinkCard.Dao;
using LinkCard.Model;
using LinkCard.Utils;

namespace LinkCard.ShopCP.PayLog
{
    public partial class Payment_delete : System.Web.UI.Page
    {
        public Int64 nPaymentID = 0;
        public Int64 nCustomerID = 0;
        public Int64 nSupplierID = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                nPaymentID = ConvertUtility.ToInt64(Request.QueryString["PayID"]);

                if (nPaymentID > 0)
                {
                    var db = new TopLinkEntities();
                    var _payLog = db.PayLog.Where(t => t.PayID == nPaymentID).FirstOrDefault();

                    nCustomerID = ConvertUtility.ToInt64(_payLog.CustomerID);
                    nSupplierID = ConvertUtility.ToInt64(_payLog.SupplierID);

                    Session["nCustomerDeleted"] = nCustomerID;
                    Session["nPaymentID"] = nPaymentID;

                    var _customer = db.Customers.Where(t => t.CustomerID == nCustomerID).FirstOrDefault();
                    var _supplier = db.Supplier.Where(t => t.SupplierID == nSupplierID).FirstOrDefault();

                    this.PaymentID.Text = nPaymentID.ToString();
                    this.PaymentDate.Text = Convert.ToDateTime(_payLog.PayDate).ToShortDateString();
                    this.CardNumber.Text = _customer.CardNumber.ToString();
                    this.FullName.Text = _customer.Fullname.ToString();

                    if (_payLog.PayMethod == 0)
                    { //0:tien mat, 1: the ngan hang, 2: doi diem
                        this.PaymentMethod.Text = "Tiền mặt";
                        this.ByCash.Text = Utility.sDecimal(ConvertUtility.ToDecimal(_payLog.PayAmount.ToString()));
                        this.ByPoint.Text = "0";
                        this.txtPayByPoint.Value = "0";
                    }
                    else if (_payLog.PayMethod == 1)
                    {
                        this.PaymentMethod.Text = "Thẻ Ngân hàng";
                        this.ByCash.Text = _payLog.PayAmount.ToString();
                        this.ByPoint.Text = "0";
                        this.txtPayByPoint.Value = "0";
                    }
                    else if (_payLog.PayMethod == 2)
                    {
                        this.PaymentMethod.Text = "Điểm LinkCard";
                        this.ByCash.Text = "0";
                        this.ByPoint.Text = _payLog.PayAmount.ToString();
                        this.txtPayByPoint.Value = _payLog.PayAmount.ToString();
                    }

                    this.PointTemp.Text = _payLog.PayPointAdd.ToString();

                    var PointPay = Convert.ToInt32(this.txtPayByPoint.Value);
                    //Thông tin trừ điểm
                    this.lblMinusPoint.Text = _payLog.PayPointAdd.ToString();
                    this.lblMinusTotalPoint.Text = (_customer.Point - _payLog.PayPointAdd + PointPay).ToString();
                    this.txtMinusTotalPoint.Value = (_customer.Point - _payLog.PayPointAdd + PointPay).ToString();
                }

            }
        }

        //Lấy về giá trị Điểm thành Tiền
        [System.Web.Services.WebMethod]
        public static string GetConfig()
        {
            try
            {
                //var iCardNumber = Convert.ToInt64(sCardNumber);
                TopLinkEntities db = new TopLinkEntities();
                var configPoint = (from q in db.Config orderby q.Version descending select q).Take(1).FirstOrDefault();

                if (configPoint != null)
                {
                    return configPoint.PointToMoney.ToString();
                }
                else
                    return "-1";
            }
            catch
            {
                return "-2";
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //Bước 1: xoá điểm của khách
            //Bước 2: xoá giao dịch
            
            //Số điện thoại của khách hàng để sms báo
            string cusPhoneNumber = "";
            string cusNewPoint = "";

            var iOldPoint = 0; //lưu lại điểm cũ phòng lỗi thì restore lại
            nCustomerID = Convert.ToInt64(Session["nCustomerDeleted"].ToString());
            nPaymentID = Convert.ToInt64(Session["nPaymentID"].ToString());

            var db = new TopLinkEntities();
            try
            {
                var _customer = db.Customers.Where(t => t.CustomerID == nCustomerID).FirstOrDefault();
                //Bước 1:
                var PointAfterDelete = Convert.ToInt32(this.txtPoint.Value.ToString());
                iOldPoint = (int)_customer.Point;
                _customer.Point = PointAfterDelete;
                
                cusNewPoint = PointAfterDelete.ToString();
                cusPhoneNumber = _customer.MobilePhone.ToString();

                db.SaveChanges();
            }
            catch
            {
 
            }
            try
            {
                var _paylog = db.PayLog.Where(t => t.PayID == nPaymentID).FirstOrDefault();
                _paylog.Status = 1;
                db.SaveChanges();
            }
            catch
            {
                var _customer = db.Customers.Where(t => t.CustomerID == nCustomerID).FirstOrDefault();
                

                _customer.Point = iOldPoint;

                db.SaveChanges();
            }

            //Lưu log
            Int64 shopStaffID = 0;
            if (Session["ShopStaffID"] != "")
                shopStaffID = Convert.ToInt64(Session["ShopStaffID"].ToString());
            var logAction = LogActions.LogItem(0, getSupplierID(), nPaymentID, nCustomerID, shopStaffID, "Xoá đơn hàng", "Delete Pay", "ShopCP");

            //Gửi tin nhắn
            if ((cusPhoneNumber != "") && cusPhoneNumber.Length >= 10)
            {
                Int64 _kqSMS = Utils.SMSTool.SendSMS(cusPhoneNumber, "Don hang: " + nPaymentID.ToString() + "da duoc xoa. Diem tich luy hien con lai la : " + cusNewPoint);
                if (_kqSMS < 0) //nếu nhắn tin lỗi thì log lại lỗi, nhắn ok thì thôi ko lưu lại nữa
                {
                    var logSMS = LogActions.LogItem(0, getSupplierID(), nPaymentID, nCustomerID, shopStaffID, "Lỗi nhắn tin: " + _kqSMS.ToString(), "Sell", "ShopCP");
                }
            }

            Response.Redirect("/message_box.aspx?msg=6");
        }

        protected Int64 getSupplierID()
        {
            try
            {

                if (Convert.ToInt32(Session["SHOPADMIN"]) == 1) // quanr ly cua hang
                {
                    Session["SupplierID"] = ConvertUtility.ToInt64(Session["USER"]);
                    return ConvertUtility.ToInt64(Session["USER"]);
                }
                else if (Convert.ToInt32(Session["SHOPADMIN"]) == 0)
                {
                    DataTable dt = LinkCard.AdminCP.Common.DataHelper.SelectTable("SELECT SupplierID FROM [ShopStaff] WHERE Username ='" + Session["USER"].ToString() + "'", false);
                    if (dt.Rows.Count > 0)
                    {
                        Session["SupplierID"] = ConvertUtility.ToInt64(dt.Rows[0]["SupplierID"]);
                        return ConvertUtility.ToInt64(dt.Rows[0]["SupplierID"]);
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch
            {
                return 0;
            }
        }
    }

}